<!--
  @author:  long
  @date:    2023/3/29
  @file:    xx
  @require:
-->
<template>
  <div class="yearSetUp">
    <el-form>
      <el-row>
        <el-col :span="24">
          <el-form-item label="年度">
            <div class="flex items-center justify-between w-full">
              <el-date-picker
                v-model="form.year"
                type="year"
                placeholder="请选择年份"
                :disabled-date="setYearDisabledDate"
                value-format="YYYY"
                format="YYYY"
                @change="selectChange"
              />
              <el-button @click="handleSave" type="primary">保存</el-button>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="考核时间">
            <div class="flex items-center justify-between w-full">
              <el-date-picker
                v-model="form.yearTimes"
                type="daterange"
                style="width: 100%"
                class="mr-2"
                ref="formDetaRef"
                value-format="YYYY-MM-DD"
                format="YYYY-MM-DD"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                :default-value="form.defaultValue"
                :disabled-date="
                  time => {
                    return setDisabledDate(time, index)
                  }
                "
              />
              <el-input v-model="form.remark" placeholder="备注"></el-input>
            </div>
            <div class="w-full">
              <el-select
                v-model="form.resultInMonth"
                multiple
                class="w-full"
                @change="handleResultInMonthChange"
              >
                <el-option-group
                  v-for="(group, index) in [previousYear, form.year, nextYear]"
                  :key="group"
                  :label="`${group}年`"
                >
                  <el-option
                    v-for="(item, i) in monthNames"
                    :key="`${index}${i}`"
                    :label="`${group}-${item}`"
                    :value="`${group}-${item}`"
                  >
                  </el-option>
                </el-option-group>
              </el-select>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script setup name="yearSetUp">
import { getCurrentInstance } from 'vue'
import { format, startOfMonth, endOfMonth } from 'date-fns'
import {
  getScheduleInfo,
  saveScheduleInfo
} from '@/api/officeManage/evaluation'
import useUserStore from '@/store/modules/user'
const { proxy } = getCurrentInstance()
const userStore = useUserStore()

const props = defineProps({
  year: {
    type: String,
    default: ''
  }
})

const data = reactive({
  form: {
    year: format(new Date(), 'yyyy'),
    yearTimes: [],
    defaultValue: [
      new Date(format(new Date(), 'yyyy-1-1')),
      new Date(format(new Date(), 'yyyy-12-31'))
    ],
    resultInMonth: '',
    assessRemark: '',
    id: ''
  },
  previousYear: format(new Date(), 'yyyy') * 1 - 1,
  nextYear: format(new Date(), 'yyyy') * 1 + 1,
  monthNames: [
    '01',
    '02',
    '03',
    '04',
    '05',
    '06',
    '07',
    '08',
    '09',
    '10',
    '11',
    '12'
  ]
})

const { form, previousYear, nextYear, monthNames } = toRefs(data)
const { month_dict } = proxy.useDict('month_dict')
const emits = defineEmits(['closeDrawer'])

/**
 * @description: 选择归属年月
 */
const handleResultInMonthChange = val => {
  let arr = val.sort()
  form.value.resultInMonth = arr
}

/**
 * @description: 保存
 */
const handleSave = () => {
  if (form.value.resultInMonth.length < 12) {
    proxy.$modal.msgWarning('至少选择12个月份')
    return
  }
  let params = []

  let obj = {
    orgId: userStore.user.orgId,
    deptId: userStore.user.deptId,
    assessAtYear: form.value.year,
    assessStime: '',
    assessEtime: '',
    assessStatus: '0',
    remark: form.value.remark,
    resultInMonth: form.value.resultInMonth.map(item => item).join(','),
    scheduleType: '2',
    id: form.value.id
  }
  if (form.value.yearTimes != null && form.value.yearTimes.length > 0) {
    obj.assessStime =
      form.value.yearTimes[0] != null
        ? form.value.yearTimes[0] + ' 00:00:00'
        : ''
    obj.assessEtime =
      form.value.yearTimes[1] != null
        ? form.value.yearTimes[1] + ' 23:59:59'
        : ''
  }
  params.push(obj)

  //   保存考评日历
  saveScheduleInfo(params).then(res => {
    if (res.code === 200) {
      proxy.$modal.msgSuccess(res.msg)
      emits('closeDrawer', form.value.year)
    }
  })
}

/**
 * @description: 月份选择
 */
const monthSelectChange = val => {
  console.info('val', val)
  // 查找month_dict符合选中的值 并设置disabled
  month_dict.value.map(item => {
    if (val.includes(item.value)) {
      item.disabled = true
    }
  })
  console.info(month_dict.value)
}

/**
 * 设置年份禁用日期
 */
const setYearDisabledDate = (time, index) => {
  let year = format(new Date(), 'yyyy') * 1
  let pre = new Date(year - 5 + '-01-01')
  let nex = new Date(year + 5 + '-12-31')
  return time < pre || time > nex
}

/**
 * @description: 设置禁用日期
 *
 */
const setDisabledDate = (time, index) => {
  return (
    time.getTime() < form.value.defaultValue[0].getTime() ||
    time.getTime() > form.value.defaultValue[1].getTime()
  )
}

/**
 * @description: 年份改变111
 */
const selectChange = () => {
  console.info(form.value.year)
  setDefaultTime()
  handleCalendarQuery()
}

/**
 * 设置默认时间
 */
const setDefaultTime = () => {
  // 根据index获取到3
  let l = new Date(`${form.value.year}-1-1`)
  let r = new Date(`${form.value.year}-12-31`)
  form.value.defaultValue = [l, r]
}

/**
 *设置form表单数据显示
 */
const setInfoData = (data, year = format(new Date(), 'yyyy')) => {
  if (data != null && data.length > 0) {
    data.forEach((item, index) => {
      form.value.yearTimes = [item.assessStime, item.assessEtime]
      form.value.resultInMonth =
        item.resultInMonth != null && item.resultInMonth != ''
          ? item.resultInMonth.split(',')
          : ''
      form.value.id = item.id
    })
  } else {
    form.value = {
      year: year + '',
      yearTimes: [],
      defaultValue: [
        new Date(format(new Date(year), 'yyyy-1-1')),
        new Date(format(new Date(year), 'yyyy-12-31'))
      ],
      resultInMonth: '',
      id: ''
    }
  }
}

/**
 * @description: 查询考评日历（季度）
 */
const handleCalendarQuery = () => {
  let params = {
    orgId: userStore.user.orgId,
    deptId: userStore.user.deptId,
    scheduleType: '2',
    assessAtYear: form.value.year
  }

  getScheduleInfo(params).then(res => {
    let data =
      res.data == null || res.data.length == 0
        ? []
        : res.data.sort((ar1, ar2) => ar1.assessAtTime - ar2.assessAtTime)
    setInfoData(data, form.value.year)
  })
}

/**
 * 初始化
 */
const init = async () => {
  setDefaultTime()

  //   设置年份
  form.value.year = props.year
  previousYear.value = props.year * 1 - 1
  nextYear.value = props.year * 1 + 10
  //   查询考评日历
  await handleCalendarQuery()
}
init()
</script>

<style scoped lang="scss">
:deep(.el-select-dropdown__wrap) {
  width: 300px !important;
}
.el-select-dropdown .el-select-dropdown__item {
  width: 25%;
  display: inline-block;
  box-sizing: border-box;
  text-align: center;
  padding: 0;
}
</style>
